<template>
  <div>
    <el-row style="margin-top: 10px">
    <el-col :span="20" style="text-align: left;" >
      <el-form ref="form" :model="searchForm" :inline="true">
        <el-form-item>
          <el-input  placeholder="根据等级查询" v-model="searchForm.keyWords" />
        </el-form-item>
        <el-button icon="el-icon-search" circle @click="search" />
        <el-button type="primary" icon="el-icon-plus" size="small" style="margin-left: 20px;
  margin-top: 5px;" @click="newAdd">新增
        </el-button>
        <el-button type="danger" v-if="selections.length>0" icon="el-icon-delete" size="small" style="
  margin-top: 5px;" @click="batchDeleteByIds">删除
        </el-button>
      </el-form>
    </el-col>
    </el-row>

    <el-row>
    <el-card class="box-card" style="margin: 5px;">
      <div slot="header" class="clearfix">
        <span>VIP管理</span>
      </div>
      <!-- vip列表-->
      <el-table :data="vips" stripe style="width: 100%" @selection-change="handleSelectionChange"
                @row-dblclick="updateSubmit" max-height="650" border>
        <el-table-column type="selection" width="50"></el-table-column>
        <el-table-column prop="grade" label="会员等级" width="180" align="center"></el-table-column>
        <el-table-column prop="cost" label="累计消费" align="center"></el-table-column>
        <el-table-column prop="discount" label="会员折扣" align="center"></el-table-column>
      </el-table>
      <!-- 分页工具条 -->
      <div style="margin-top: 10px" class="block">
        <el-pagination
          :page-sizes="pageSizes"
          :page-size="pageSize"
          :current-page="currentPage"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    </el-row>

    <!-- 添加/编辑 界面 -->
    <el-dialog title="VIP信息" :visible.sync="dialogVisible" width="30%">
      <el-form :model="editForm"
               :rules="rules"
               ref="ruleForm"
               label-width="100px" class="demo-ruleForm">

        <el-form-item label="会员等级" prop="grade">
          <el-input v-model="editForm.grade"></el-input>
        </el-form-item>

        <el-form-item label="累计消费" prop="cost">
          <el-input v-model="editForm.cost"  type="textarea" :rows="5" placeholder="请输入累计消费"></el-input>
        </el-form-item>

        <el-form-item label="会员折扣(%)" prop="discount">
          <el-input v-model.number="editForm.discount"></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')">确认提交</el-button>
          <el-button @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

  </div>

</template>
<script>
  export default {
    data() {
      //校验折扣
      var checkDiscount = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('折扣不能为空或0'));
        }
        setTimeout(() => {
          if (!Number.isInteger(value)) {
            callback(new Error('请输入数字值'));
          } else {
            if (value > 100 || value <= 0) {
              callback(new Error('折扣介于0~100之间'));
            } else {
              callback();
            }
          }
        }, 500);
      };
      return {
        vips: [],
        pageNo: 1,
        pageSize: 10,
        total: 0,
        pageSizes: [5, 10, 15, 20],
        currentPage:1,
        keyWord:"",

        // 添加/编辑表单属性
        editForm: {
          id: '',
          grade: "",
          cost: "",
          discount: ""
        },
        dialogVisible: false,

        // 验证规则
        rules: {
          grade: [
            {required: true, message: '请输入会员等级', trigger: 'blur'},
          ],
          cost: [
            {required: true, message: '请输入累计消费', trigger: 'change'}
          ],
          discount: [
            {validator: checkDiscount, trigger: 'blur'}
          ]
        },

        //复选框选中行
        selections: [],

        //搜索框中
        searchForm:{
          keyWords:""
        }
      }
    },
    methods: {
      //加载列表数据
      getVips() {
        //获取参数
          //当前页码
          //页码最大记录数
          //搜索关键词
        let params = {
          pageNo:this.currentPage,
          pageSize:this.pageSize,
          keyWord:this.searchForm.keyWords
        };

        //发送请求到后台查询数据axios
        this.$http.post('/vip/findForList',params).then(res => {
          this.vips = res.data.data.result;
          this.currentPage=res.data.data.pageNo;
          this.total=res.data.data.total;
        })
      },

      //页码大小发生变化
      handleSizeChange(pageSize) {
        this.pageSize = pageSize;
        this.getVips();
      },

      //当前页码发生变化
      handleCurrentChange(currentPage) {
        this.currentPage = currentPage;
        this.getVips();
      },

      //添加按钮
      newAdd() {
        this.editForm.id="";  //清空编辑留下的id
        this.dialogVisible = true;
        this.$nextTick(() => {
          this.$refs['ruleForm'].resetFields();//重置表单
        })
      },

      //修改按钮
      updateSubmit(row) {
        this.dialogVisible = true;
        this.$nextTick(() => {
          this.$refs['ruleForm'].resetFields();//重置表单
          this.editForm = $.extend({}, row);  //回显
          this.editForm.discount = parseInt(100 * this.editForm.discount);  //折扣转换为整型
        })
      },

      //提交表单
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {  //如果验证通过
            //判断当前id是否有值
            //如果id没有值为添加请求
            //默认请求地址为添加请求
            let url = "/vip/insert";
            //修改
            if (this.editForm.id){
                url = "/vip/update";   //如果id有值为修改请求
              //克隆表单中的数据
              let params = Object.assign({}, this.editForm);
              params.discount = this.changeDiscount();   //更新折扣为小数
              this.$http.put(url,params)
                .then((res)=>{
                  if(res.data.success){
                    this.$message({
                      showClose: true,
                      message: '修改成功',
                      type: 'success'
                    });
                    this.dialogVisible = false;
                    this.getVips();
                  }else{
                    this.$message({
                      showClose: true,
                      message: '修改失败【'+res.message+"】",
                      type: 'error'
                    });
                  }
                })
                .catch((error)=>{
                  this.$message({
                    showClose: true,
                    message: '操作失败【'+error.message+"】,请联系攻城狮",
                    type: 'error'
                  });
                })
            }else{      //添加
              //克隆表单中的数据
              let params = Object.assign({}, this.editForm);
              params.discount = this.changeDiscount();   //更新折扣为小数

              this.$http.post(url,params)
                .then((res)=>{
                  if(res.data.success){
                    this.$message({
                      showClose: true,
                      message: '添加成功',
                      type: 'success'
                    });
                    this.dialogVisible = false;
                    this.getVips();
                  }else{
                    this.$message({
                      showClose: true,
                      message: '添加失败【'+res.message+"】",
                      type: 'error'
                    });
                  }
                })
                .catch((error)=>{
                  this.$message({
                    showClose: true,
                    message: '操作失败【'+error.message+"】,请联系攻城狮",
                    type: 'error'
                  });
                })
              }
          }
        });
      },

      //重置表单
      resetForm(formName) {
        this.$nextTick(() => {
          this.$refs['ruleForm'].resetFields();/*清空*/
        })
      },

      //将折扣改为小数
      changeDiscount(){
        return 0.01 * this.editForm.discount;
      },

      //当选中的行改变时 参数为当前行
      handleSelectionChange(selection) {
        this.selections = selection;
      },

      //根据选中行删除数据
      batchDeleteByIds(){

        //遍历选中所有行,并将id值组成数组
        let ids = this.selections.map(item=>item.id);

        //将这个数组作为对象中的数组
        let params = {"ids":ids};

        //删除数据
          this.$http.post("/vip/batchDeleteByIds",params)
            .then((res)=>{
              this.$confirm('是否删除', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              }).then(() => {
                if(res.data.success){
                  this.$message({
                    showClose: true,
                    message: '删除成功',
                    type: 'success'
                  });
                  this.dialogVisible = false;
                  this.getVips();
                }else{
                  this.$message({
                    showClose: true,
                    message: '删除失败【'+res.message+"】",
                    type: 'error'
                  });
                }
              });
            })
            .catch((error)=>{
              this.$message({
                showClose: true,
                message: '操作失败【'+error.message+"】,请联系攻城狮",
                type: 'error'
              });
            })
        },
      //搜索
      search(){
        this.currentPage = 1;
        this.getVips();
      }

    },
    mounted() {
      this.getVips();
    }
  }
</script>
